<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/user.jsp"%>
<%
	Integer pid = input.getInt("pid", 0);
	Integer uid = token.getUid(); 
	Integer patientUid = input.getInt("patient_uid", -1);
	if (patientUid != -1) {
		uid = patientUid;
		if (!validateReportAuth(token, patientUid)) {
			msg.setErrcodeAndErrmsg(30021, "您没有权限查看该患者的检验报告");
			Tools.encryptPrint(out, msg); 
			return;
		}
		UserProfile selfProfile = selfProfileByUid(uid);
		if (selfProfile != null) 
			pid = selfProfile.getId();
	}
	Integer branch = input.getInt("branch", 1);
	String where = "";
	if (hospital != 999)
		where = " and hospital=" + hospital +" and branch = " + branch  ;
	Map<Integer, UserProfile> userprofileMap = userprofileByUid(uid);
	Map<String, Integer> cardMap = new HashMap<String, Integer>();
	String hql = "";
	if (pid == 0) { // 查全部就诊人
		String cards = "'-1'";
		for (Integer key : userprofileMap.keySet()) {
			UserProfile up = userprofileMap.get(key);
			String cardNumber = up.getCardNumber();
			cardMap.put(cardNumber, key);
			cards += ",'" + cardNumber + "'";
		}
		hql = "select distinct new map(patientName as patient_name, branchName as branch_name, sampleNo as sample_no, parentItemName as name, receiveTime as created_time, cardNumber as card_number, hospital as hospital) from Examine where card_number in (" + cards + ") " +  where +  " order by receive_time desc";
	} else {
		UserProfile userprofile = userprofileMap.get(pid);
		if (userprofile == null) {
			msg.setErrcodeAndErrmsg(30021, "pid不属于该用户");
			Tools.encryptPrint(out, msg); 
			return;
		}
		String cardNumber = userprofile.getCardNumber();
		hql = "select distinct new map(patientName as patient_name, branchName as branch_name, sampleNo as sample_no, parentItemName as name, receiveTime as created_time, cardNumber as card_number, hospital as hospital) from Examine where card_number = '" + cardNumber + "' " + where + " order by receive_time desc";
	}
	
	List examineList = QBuilder.db("basedb").queryHql(hql);
	for (int i = 0; i < examineList.size(); i++) {
		Map ma = (Map)examineList.get(i);
		String cardNumber = Tools.getDesc(ma.get("card_number"), "");
		ma.put("pid", cardMap.get(cardNumber));
		ma.remove("card_number");
	}
	completeHospitalInfo(examineList);
	msg.put("data", examineList);
	Tools.encryptPrint(out, msg);
%>
